package com.myx.juc.threadpool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述:ThreadPool 简单使用
 * @author: myx
 * @date: 2018/11/23
 * Copyright © 2018-hotpot. All rights reserved.
 */
public class ThreadPoolDemo {
    public static void main(String[] args) throws InterruptedException {
        Lock lock =new ReentrantLock();
        Long start= System.currentTimeMillis();
        //为保证线程安全需要加入Collections.synchronizedList   或者直接加synchronized(list)
        final List<Integer> list= Collections.synchronizedList(new ArrayList<Integer>());
        ExecutorService executorService = Executors.newCachedThreadPool();
        new Thread(new MonitorThreadPoolUtil((ThreadPoolExecutor) executorService,1)).start();
        for(int i=0;i<100000;i++){
            final int j=i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    //这里不加同步会出现list数量每次不一致
                    list.add(j);
                }
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.DAYS);
        System.out.println(System.currentTimeMillis()-start);
        System.out.println(list.size());
    }

}
